<?php

class HecUserController extends AController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='/layouts/column5';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			//'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new HecUser;
		$userDepartmentModel = new UserDepartment;
		$userCodeModel = new UserCode;

		$departmentOption = $userDepartmentModel->getOptions(1);
		$buOption = $userDepartmentModel->getOptions(0);
		$codeOption = $userCodeModel->getOptions();
		$statusOption = $userDepartmentModel->statusOption();
		//$ynOption = $model->ynOption();
		$attrOption = $model->getAttribute();
		$companyOption = $model->getCompany();
		$workTypeOption = $model->getWorkType();
		$genderOption = $model->getGender();

		if(isset($_POST['action']) && ($_POST['action'] == 'create'))
		{
			$model->unique_id = $_POST['unique_id'];
			$model->username = $_POST['username'];
			$model->c_username = $_POST['c_username'];
			$model->email = $_POST['email'];
			$model->birthday = $_POST['birthday'];
			$model->mobile = $_POST['mobile'];
			$model->department = $_POST['department'];
			$model->bu = $_POST['bu'];
			$model->code = $_POST['code'];
			$model->company = $_POST['company'];
			$model->attribute = $_POST['attribute'];
			$model->position = $_POST['position'];
			$model->work_type = $_POST['work_type'];
			$model->entry_point = $_POST['entry_point'];
			$model->gender = $_POST['gender'];
			$model->probation = $_POST['probation'];
			$model->status = $_POST['status'];
			$model->dateline = $_SERVER['REQUEST_TIME'];
			if($model->save())
				$this->showAlert(array('type'=>'1','content'=>'添加成功！','url'=>'admincp/hecUser/index'));
		}

		$this->render('create',array(
			'model'=>$model,'departmentOption'=>$departmentOption,'statusOption'=>$statusOption,'attrOption'=>$attrOption,'companyOption'=>$companyOption,'codeOption'=>$codeOption,'buOption' => $buOption,'workTypeOption' => $workTypeOption , 'genderOption' => $genderOption
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['action']) && ($_POST['action'] == 'update'))
		{
			$model = $this->loadModel((int)$_POST['id']);
			$model->unique_id = $_POST['unique_id'];
			$model->username = $_POST['username'];
			$model->c_username = $_POST['c_username'];
			$model->email = $_POST['email'];
			$model->birthday = $_POST['birthday'];
			$model->mobile = $_POST['mobile'];
			$model->department = $_POST['department'];
			$model->bu = $_POST['bu'];
			$model->code = $_POST['code'];
			$model->company = $_POST['company'];
			$model->attribute = $_POST['attribute'];
			$model->position = $_POST['position'];
			$model->work_type = $_POST['work_type'];
			$model->entry_point = $_POST['entry_point'];
			$model->gender = $_POST['gender'];
			$model->probation = $_POST['probation'];
			$model->status = $_POST['status'];
			$model->dateline = $_SERVER['REQUEST_TIME'];
			if($model->save())
				$this->showAlert(array('type'=>'1','content'=>'更新成功！','url'=>'admincp/hecUser/update/id/'.(int)$_POST['id']));
		}
		else
		{
			$userDepartmentModel = new UserDepartment;
			$userCodeModel = new UserCode;
			$departmentOption = $userDepartmentModel->getOptions(1);
			$buOption = $userDepartmentModel->getOptions(0);
			$codeOption = $userCodeModel->getOptions();
			$statusOption = $userDepartmentModel->statusOption();
			$attrOption = $model->getAttribute();
			$companyOption = $model->getCompany();
			$workTypeOption = $model->getWorkType();
			$genderOption = $model->getGender();
			//获取元素的级别
			//$userPositionLevelModel = new UserPositionLevel;
			$userLevel = UserPositionLevel::model()->findByAttributes(array('unique_id' => $model->unique_id),array('order'=>'dateline DESC','limit'=>'1'));
			//获取所有职位描述
			$positionLevelsL = HrPositionLevel::model()->findAllByAttributes(array('status' => 1),' Level like "L%"');
			$positionLevelOptionL[0] = '请选择';
			foreach ($positionLevelsL as $value) {
				$positionLevelOptionL[$value['id']] = $value['name'];
			}
			$positionLevelsM = HrPositionLevel::model()->findAllByAttributes(array('status' => 1),' Level like "M%"');
			$positionLevelOptionM[0] = '请选择';
			foreach ($positionLevelsM as $value) {
				$positionLevelOptionM[$value['id']] = $value['name'];
			}
			//$hrPositionAttributeModel = new HrPostionAttribute;
			$pa =  HrPositionAttribute::model()->findAll();
			$paOption[0] = '请选择';
			foreach ($pa as $key => $value) {
				$paOption[$value['id']] = $value['title'];
			}
		}

		$this->render('update',array(
			'model'=>$model,'departmentOption'=>$departmentOption,'statusOption'=>$statusOption,'attrOption'=>$attrOption,'companyOption'=>$companyOption,'codeOption'=>$codeOption,'userLevel'=>$userLevel,'positionLevelOptionL'=>$positionLevelOptionL,'positionLevelOptionM'=>$positionLevelOptionM,'paOption' => $paOption ,'buOption' => $buOption,'workTypeOption' => $workTypeOption , 'genderOption' => $genderOption
		));
	}

	public function actionDetail($id)
	{
		$model=$this->loadModel($id);
		$userDepartmentModel = new UserDepartment;
		$userCodeModel = new UserCode;
		$departmentOption = $userDepartmentModel->getOptions();
		$codeOption = $userCodeModel->getOptions();
		$statusOption = $userDepartmentModel->statusOption();
		$attrOption = $model->getAttribute();
		$companyOption = $model->getCompany();
		//获取元素的级别
		$userPositionLevelModel = new UserPositionLevel;
		$userLevel = UserPositionLevel::model()->findByAttributes(array('unique_id' => $model->unique_id));
		//获取所有职位描述
		$positionLevelsL = HrPositionLevel::model()->findAllByAttributes(array('status' => 1),' Level like "L%"');
		$positionLevelOptionL[0] = '请选择';
		foreach ($positionLevelsL as $value) {
			$positionLevelOptionL[$value['id']] = $value['name'];
		}
		$positionLevelsM = HrPositionLevel::model()->findAllByAttributes(array('status' => 1),' Level like "M%"');
		$positionLevelOptionM[0] = '请选择';
		foreach ($positionLevelsM as $value) {
			$positionLevelOptionM[$value['id']] = $value['name'];
		}

		$this->render('detail',array(
			'model'=>$model,'departmentOption'=>$departmentOption,'statusOption'=>$statusOption,'attrOption'=>$attrOption,'companyOption'=>$companyOption,'codeOption'=>$codeOption,'userLevel'=>$userLevel,'positionLevelOptionL'=>$positionLevelOptionL,'positionLevelOptionM'=>$positionLevelOptionM
		));
	}

	public function actionUpdateUserLevel()
	{
		$userLevelModel = new UserPositionLevel;
		//print_r($_POST);
		//die;
		//$userLevel = UserPositionLevel::model()->findByAttributes(array('unique_id' => $_POST['unique_id']));
		$error = 0;
		$model = new UserPositionLevel;
		$model->updateStatus($_POST['unique_id']);
		$model->unique_id = $_POST['unique_id'];
		$model->attr_id = $_POST['attr_id'];
		$model->attr_M_id = $_POST['attr_M_id'];
		$model->attr_L_id = $_POST['attr_L_id'];
		$model->title = $_POST['title'];
		$model->title_en = $_POST['title_en'];
		$model->B = $_POST['B'];
		$model->status = 1;
		$model->dateline = $_SERVER['REQUEST_TIME'];
		$model->save();
		//}
		echo $error;
		//echo '22';
	}

	public function actionCreateUserLevel()
	{
		$error = 0;
		$model = new UserPositionLevel;
		$model->updateStatus($_POST['unique_id']);
		$model->unique_id = $_POST['unique_id'];
		$model->attr_id = $_POST['attr_id'];
		$model->attr_M_id = $_POST['attr_M_id'];
		$model->attr_L_id = $_POST['attr_L_id'];
		$model->title = $_POST['title'];
		$model->title_en = $_POST['title_en'];
		$model->B = $_POST['B'];
		$model->status = 1;
		$model->dateline = $_SERVER['REQUEST_TIME'];
		$model->save();
		echo $error;
	}



	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$condition = " 1=1 ";
		if(isset($_GET['search']))
		{
			//print_r($_GET);
			
			if($_GET['search']['s_username'])
			{
				$condition .= " AND ( username LIKE '%".urldecode($_GET['search']['s_username'])."%' OR c_username LIKE '%".urldecode($_GET['search']['s_username'])."%' OR unique_id LIKE '%".urldecode($_GET['search']['s_username'])."%' ) ";
			} 
			if($_GET['search']['s_department'])
			{
				$condition .= "AND department = '".$_GET['search']['s_department']."' ";
			}
			if($_GET['search']['s_code'])
			{
				$condition .= "AND code = '".$_GET['search']['s_code']."' ";
			}
			if($_GET['search']['s_company'])
			{
				$condition .= "AND company = '".$_GET['search']['s_company']."' ";
			}
			if(isset($_GET['search']['s_status']))
			{
				$condition .= "AND status = '".$_GET['search']['s_status']."' ";
			}
		}
		else
			$condition .= "AND status = '1' ";
		//echo $condition;
		$serch = isset($_GET['search'])?$_GET['search']:array();
		$model=new HecUser();
		$userDepartmentModel = new UserDepartment;
		$userCodeModel = new UserCode;
		$departmentOption = $userDepartmentModel->getOptions();
		$codeOption = $userCodeModel->getOptions();
		$statusOption = $userDepartmentModel->statusOption();
		$companyOption = $model->getCompany();
		$search = isset($_GET['search'])?$_GET['search']:array();

		$pageSize = ($_GET['search']['type'] == 'csv') ? 10000 : 30;

		$dataProvider = new CActiveDataProvider('HecUser',array(
			'criteria'=>array(
				'order' => 'id DESC',
				'condition' => $condition
				),
			'pagination'=>array(
		        'pageSize'=>$pageSize,
		    	),
			)
		); 

		if($_GET['search']['type'] == 'csv')
		{
			$arr = $dataProvider->getData() ;
			foreach ($arr as $key => $value)
			{
				
			}
			Csv::exportCsv(Yii::app()->params['userFields'],$arr);
			Yii::app()->end();
		}

		$this->render('index',array('dataProvider'=>$dataProvider,'departmentOption'=>$departmentOption,'codeOption'=>$codeOption,'statusOption'=>$statusOption,'companyOption'=>$companyOption ,'search'=>$search));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new HecUser('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['HecUser']))
			$model->attributes=$_GET['HecUser'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=HecUser::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='hec-user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}


	/**
	 * export csv data
	 *
	 */
	public function actionExportCsv()
	{



	}
}
